﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Davsha.App.Actions
{
    class BringWindowToFront : IAction
    {
        public void Execute(ActionParameterCollection parameters)
        {
            string processName = parameters["ProcessName"];
            string windowTitle = parameters.TryGetParameterValue("WindowTitle");

            Process[] processes = Process.GetProcessesByName(processName);

            if (processes.Length == 0)
            {
                throw new Exception("Process not found: " + processName);
            }

            Process p = processes[0];

            EnumWindows(new EnumWindowsProc(delegate(IntPtr hwnd, IntPtr lParam)
            {
                int pid;
                GetWindowThreadProcessId(hwnd, out pid);

                if (pid == p.Id)
                {
                    if (windowTitle != null)
                    {
                        StringBuilder sb = new StringBuilder(GetWindowTextLength(hwnd) + 1);
                        GetWindowText(hwnd, sb, sb.Capacity);

                        if (!windowTitle.Equals(sb.ToString()))
                        {
                            return 1;
                        }
                    }

                    SetForegroundWindow(hwnd);
                    return 0;
                }

                return 1;
            }), new IntPtr(0));

        }

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd); 

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        private delegate int EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int GetWindowTextLength(IntPtr hWnd);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);
    }
}
